package com.crazy.crazytransactionservice.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crazy.crazycommon.common.ErrorCode;
import com.crazy.crazycommon.constant.ShareRecordTypeConstant;
import com.crazy.crazycommon.exception.BusinessException;
import com.crazy.crazymodel.model.entity.Position;
import com.crazy.crazymodel.model.entity.Product;
import com.crazy.crazymodel.model.entity.ShareRecord;
import com.crazy.crazymodel.model.vo.BankCardAndShare;
import com.crazy.crazymodel.model.vo.PageBankCardAndShareVO;
import com.crazy.crazymodel.model.vo.ProductPositonVO;
import com.crazy.crazyserviceclient.service.ProductFeignClient;
import com.crazy.crazytransactionservice.mapper.PositionMapper;
import com.crazy.crazytransactionservice.mapper.ShareRecordMapper;
import com.crazy.crazytransactionservice.model.ProductAndShare;
import com.crazy.crazytransactionservice.service.PositionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class PositionServiceImpl extends ServiceImpl<PositionMapper,Position> implements PositionService {
    @Resource
    private ProductFeignClient productFeignClient;
    @Resource
    private PositionMapper positionMapper;

    @Resource
    private ShareRecordMapper shareRecordMapper;

    /**
     * 获取该用户的产品持仓情况   需分页
     * @param customerID
     * @return
     */
    @Override
    public PageBankCardAndShareVO getProductsPosition(int customerID, int current) {
        PageBankCardAndShareVO pageBankCardAndShareVO=new PageBankCardAndShareVO();
        List<ProductPositonVO> productPositonVOList=new ArrayList<>();

        //从持仓表中统计出该用户持仓的  产品id 总份额 总冻结份额
        //分页查询
        int size=10;//每页记录数定为10
        IPage<ProductAndShare> page = new Page<>(current,size);
        positionMapper.getProductAndShare(page, customerID);
        List<ProductAndShare> list=page.getRecords();

        if(list.isEmpty()) {
            log.info("该用户没有持仓记录");
        }
        for (ProductAndShare item : list) {
            ProductPositonVO productPositonVO=new ProductPositonVO();
            //获取产品信息
            Product product = productFeignClient.getById(item.getProductID());
            if(product == null) throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"产品不存在");
            //set 产品信息
            productPositonVO.setProductID(product.getProductID());
            productPositonVO.setProductCode(product.getProductCode());
            productPositonVO.setProductName(product.getProductName());
            productPositonVO.setProductType(product.getProductType());
            productPositonVO.setRiskLevel(product.getRiskLevel());

            //set 总有效份额
            productPositonVO.setTotalShare(item.getTotalShare().subtract(item.getTotalFreezeShare()));
            //获取 银行卡和份额数组
            List<BankCardAndShare> bankCardAndShares=positionMapper.getBankCardAndShare(customerID, item.getProductID());
            productPositonVO.setBankcards(bankCardAndShares);

            //添加到list里
            productPositonVOList.add(productPositonVO);

        }
        //
        pageBankCardAndShareVO.setTotal(page.getTotal());
        pageBankCardAndShareVO.setCurrent(page.getCurrent());
        pageBankCardAndShareVO.setSize(page.getSize());
        pageBankCardAndShareVO.setProducts(productPositonVOList);
        return pageBankCardAndShareVO;
    }

    /**
     * 获取某个position记录
     * @param customerID
     * @param productID
     * @param bankCardNumber
     * @return
     */
    @Override
    public Position getPosition(int customerID, int productID, String bankCardNumber) {
        //找到这个position
        Position position = lambdaQuery().eq(Position::getCustomerID, customerID)
                .eq(Position::getProductID, productID)
                .eq(Position::getBankCardNumber, bankCardNumber)
                .one();
        if(position==null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "该持仓不存在");
        }
        return position;
    }

    /**
     * 提交赎回申请后 冻结份额
     * @param customerID
     * @param productID
     * @param freezeShare
     * @param bankCardNumber
     * @return
     */
    @Override
    public Void FreezeShares(int customerID, int productID, BigDecimal freezeShare, String bankCardNumber) {
        //更新 freezeShare 字段
        lambdaUpdate()
                .eq(Position::getCustomerID, customerID)
                .eq(Position::getProductID, productID)
                .eq(Position::getBankCardNumber, bankCardNumber)
                .set(Position::getFreezeShare,freezeShare)
                .set(Position::getUpdateTime,new Date(System.currentTimeMillis()))
                .update();
        return null;
    }

    /**
     * 取消赎回后 需要解冻
     * @param customerID
     * @param productID
     * @param share
     * @param bankCardNumber
     * @return
     */
    @Override
    public Void cancelFreeze(int customerID, int productID, BigDecimal share, String bankCardNumber) {
        boolean update = lambdaUpdate()
                .eq(Position::getCustomerID, customerID)
                .eq(Position::getProductID, productID)
                .eq(Position::getBankCardNumber, bankCardNumber)
                .setSql("freezeShare = freezeShare - " + share)
                .set(Position::getUpdateTime,new Date(System.currentTimeMillis()))
                .update();
        if(!update){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"取消赎回订单时，解冻冻结金额出错");
        }

        return null;
    }

    /**
     * 确认赎回后 更新持仓表
     * 还要添加份额流水到份额流水表中
     * @param customerID
     * @param productID
     * @param share
     * @param bankCardNumber
     * @return
     */
    @Override
    @Transactional
    public Void confirmRedeem(int customerID, int productID, BigDecimal share,BigDecimal amount, String bankCardNumber) {
        //确认赎回，修改冻结份额、份额和持仓金额
        boolean update = lambdaUpdate()
                .eq(Position::getCustomerID, customerID)
                .eq(Position::getProductID, productID)
                .eq(Position::getBankCardNumber, bankCardNumber)
                .setSql("freezeShare = freezeShare - " + share)
                .setSql("share = share - " + share)
                .setSql("amount = amount - " +amount)
                .set(Position::getUpdateTime,new Date(System.currentTimeMillis()))
                .update();
        if(!update){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"确认赎回时，更新持仓表失败");
        }


        Position position1 = getPosition(customerID, productID, bankCardNumber);
        BigDecimal currentShare = position1.getShare();//变化后的份额

        //将份额变化加入到份额流水表里
        ShareRecord shareRecord=new ShareRecord();
        shareRecord.setChangeShare(share.negate());//负数
        shareRecord.setProductID(productID);
        shareRecord.setCustomerID(customerID);
        shareRecord.setActionType(ShareRecordTypeConstant.REDEEM);
        shareRecord.setBankCardNumber(bankCardNumber);
        shareRecord.setCurrentShare(currentShare);
        shareRecord.setChangeTime(new Date(System.currentTimeMillis()));
        shareRecordMapper.insert(shareRecord);

        //确认赎回时，还需要判断是不是全部赎回了，份额为0时需要移除这条持仓记录
        Position position = lambdaQuery()
                .eq(Position::getCustomerID, customerID)
                .eq(Position::getProductID, productID)
                .eq(Position::getBankCardNumber, bankCardNumber).one();

        if(position!=null&&position.getShare().compareTo(BigDecimal.ZERO) == 0){
            boolean remove = lambdaUpdate()
                    .eq(Position::getCustomerID, customerID)
                    .eq(Position::getProductID, productID)
                    .eq(Position::getBankCardNumber, bankCardNumber).remove();
            if(!remove){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"删除无效持仓记录时失败");
            }
        }
        return null;
    }
}
